package com.dyl.vod.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.dyl.common.core.exception.BaseException;
import com.dyl.vod.service.VideoService;
import com.dyl.vod.utils.VodCofigUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class VideoServiceImpl implements VideoService {

    /**
     * 获取阿里云视频点播服务的视频播放地址
     *
     * @param videoId 阿里云视频点播中的视频ID
     * @return 视频播放地址
     */
    public  String getVideoPlayUrl(String videoId) {
        DefaultProfile defaultProfile = DefaultProfile.getProfile("cn-shanghai", VodCofigUtils.ACCESS_KEY_ID,  VodCofigUtils.ACCESS_KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(defaultProfile);

        GetPlayInfoRequest request = new GetPlayInfoRequest();
        request.setVideoId(videoId);

        GetPlayInfoResponse response;
        try {
            response = client.getAcsResponse(request);
        } catch (ClientException e) {
            if ("InvalidVideo.NotFound".equals(e.getErrCode())) {
                throw new BaseException("视频点播获取失败/videoid错误或者不存在",20002,"videoid错误或者不存在");
            } else {
                // 处理其他异常的逻辑
                e.printStackTrace();
            }
            return null;
        }

        List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
        if (playInfoList != null && !playInfoList.isEmpty()) {
            return playInfoList.get(0).getPlayURL();
        } else {
            return null;
        }
    }
}
